﻿using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Reflection;
using QbservableCore.Serialization.Helpers;
using System.Runtime.Serialization;

namespace QbservableCore.Serialization
{
    [DataContract]
    public class PropertyOrFieldNode : ExpRepresentationBase
    {
        [DataMember]
        public ExpRepresentationBase Target { get; set; }

        [DataMember]
        public SerializableMemberInfo MemberToken { get; set; }

        [DataMember]
        public string MemberName { get; set; }

        protected internal override Expression ToExpression(ExepressionBuilderCache exepressionBuilderCache)
        {
            Expression target = Target == null ? null : Target.ToExpression(exepressionBuilderCache);
            MemberInfo member = MemberToken.Deserialize();
            return Expression.MakeMemberAccess(target, member);
        }

        protected override void TraverseChildren(Func<ExpRepresentationBase, ExpRepresentationBase> action)
        {
            if (Target != null)
            {
                Target = Target.Traverse(action);
            }
        }

        public override string ToString()
        {
            return string.Format("{0}.{1}", Target, MemberName);
        }
    }
}